	var MHM = new Object();

	var maxTries = 0;
	MHM.itemsperpage = 4;
	MHM.cpEvent = 0;
	MHM.tpEvent = 0;
	MHM.cpHelpDesk = 0;
	MHM.tpHelpDesk = 0;
	MHM.cpEmail = 0;
	MHM.tpEmail = 0;
	MHM.totalticketpriorities = 0;
	MHM.totalticketstatus = 0;
	MHM.totalticketseverities = 0;
	
	MHM.visible = function(name) {
		if (document.getElementById(name) != null) {
			if (document.getElementById(name).innerHTML.length < 2) {
				var dt = name + "_dt";
				document.getElementById(name).style.display = "none";
				document.getElementById(dt).style.display = "none";
			}
		}
	}
	MHM.setvals = function() {
		document.getElementById("settings").style.visibility = "none";
		document.getElementById("mm_0").innerHTML = "";
		maxTries = 0;
		MHM.challenge();
	}	

// Step6: Call webservice of VT to execute operation
	MHM.getoperation = function(getstring,getresponse, cache) {
		var params = {};  
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = cache;
		var url = vtigerurl + "/webservice.php?" + getstring; 
		gadgets.io.makeRequest(url, getresponse, params);
	}
	MHM.postoperation = function(postdata,postresponse,cache) {
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;  
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
		params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = cache;
		var url = vtigerurl + "/webservice.php";
		gadgets.io.makeRequest(url, postresponse, params); 
	}
	// Step3: login to VT
	MHM.challengeresponse = function(obj) {
		var response = obj.data;		
		//console.log(response);
		var token = response['result']['token'];		
		var hash = MD5(token + accesskey);
		var postdata = {};
		postdata.operation = "login";
		postdata.username = userName;
		postdata.accessKey = hash;
		MHM.postoperation(postdata,MHM.loginresponse,300);
	}
	// Step4: Get email mathch with extractedText = sender email
	MHM.loginresponse = function(obj) {
		var response = obj.data;
		if (response['success'] == false) {
			// Automatically attempt to login again
			if(maxTries < 5) {
				maxTries++;
				msg.createDismissibleMessage("Attempt to login again (" + maxTries +")");
				setTimeout("MHM.challenge()",5000);
			} else {
				msg.createDismissibleMessage("Login failed:" + response['error']['message']);
			}
		} else {
			MHM.sessionname = response['result']['sessionName'];
			MHM.userId = response['result']['userId'];			
			MHM.getListUsers();
			MHM.getPicklist('HelpDesk');
			MHM.search(extractedText, 'Contacts');			
		}
	};
	
	MHM.logout = function(sessionname) {
		logoutstring = "operation=logout&sessionName=" + sessionname;
		MHM.getoperation(logoutstring,MHM.logoutresponse,0);
	}
	
	MHM.logoutresponse = function(obj) {
		var response = obj.data;
		if (response['success'] == false) {
			MHM.displayerror(response, "Logout failed");
		}
		else {
			var logoutStatus = response['result']['message'];
			document.getElementById('content_div2').innerHTML = "Logout:" + logoutStatus;
		}
	}

	MHM.getPicklist = function(module) {		
		querystring = "operation=describe&sessionName=" + MHM.sessionname + "&elementType="+module;
//		var functionname = "MHM.get"+module+"Picklist";
		MHM.getoperation(querystring,MHM.getHelpDeskPicklist,360);
	}

	MHM.getHelpDeskPicklist = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
		}else{
			MHM.ticketpriorities = new Array();
			MHM.ticketseverities = new Array();
			MHM.ticketstatus = new Array();
			
			
			var result = response['result']['fields'];
			var length = result.length;
//			alert(length);

			for (var i=0; i<length; i++){
				if (result[i]['name'] == 'ticketpriorities'){
					var picklist_arr = result[i]['type']['picklistValues'];
//					alert(picklist_arr.length);
					for (var j=0; j<picklist_arr.length;j++){
						MHM.ticketpriorities[MHM.totalticketpriorities] = {};
						MHM.ticketpriorities[MHM.totalticketpriorities].label = picklist_arr[j]['label'];
						MHM.ticketpriorities[MHM.totalticketpriorities].value = picklist_arr[j]['value'];
						MHM.totalticketpriorities++;
					}
				}
				
				if (result[i]['name'] == 'ticketseverities'){
					var picklist_arr = result[i]['type']['picklistValues'];
//					alert(picklist_arr.length);
					for (var j=0; j<picklist_arr.length;j++){
						MHM.ticketseverities[MHM.totalticketseverities] = {};
						MHM.ticketseverities[MHM.totalticketseverities].label = picklist_arr[j]['label'];
						MHM.ticketseverities[MHM.totalticketseverities].value = picklist_arr[j]['value'];
						MHM.totalticketseverities++;
					}
				}				
			
				if (result[i]['name'] == 'ticketstatus'){
					var picklist_arr = result[i]['type']['picklistValues'];
//					alert(picklist_arr.length);
					for (var j=0; j<picklist_arr.length;j++){
						MHM.ticketstatus[MHM.totalticketstatus] = {};
						MHM.ticketstatus[MHM.totalticketstatus].label = picklist_arr[j]['label'];
						MHM.ticketstatus[MHM.totalticketstatus].value = picklist_arr[j]['value'];
						MHM.totalticketstatus++;
					}
				}
								
			}
			
//			alert(MHM.totalticketpriorities);
			for (var i=0; i<MHM.totalticketpriorities; i++){
//				alert("label = "+MHM.ticketpriorities[i].label+" value = "+MHM.ticketpriorities[i].value);
			}
			
//			alert((response['result']['fields'][0]['type']['picklistValues'] != null)
		}
	}
	
	MHM.getListUsers = function() {
		queryparam ="SELECT * FROM Users;";
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.getListUsersResult,600);
	}
	
	MHM.getListUsersResult = function(obj) {
		var response = obj.data;
		if (typeof obj.data=='undefined' || response['success'] == false){
			MHM.displayerror(response, "get list users failed");			
		} else {
			if (response['result'][0] != null) {
				MHM.listUsers = new Array();
				for(i = 0;i < response.result.length;i++) {
					MHM.listUsers[response.result[i].id] = response.result[i].user_name;
				}
			}
		}
	}
	
	// search match sender email
	MHM.search = function(extractedemail, module) {
		queryparam ="SELECT * FROM " + module + " WHERE email='" + extractedemail + "';"; 
		if(module == 'Users' || module=='Accounts') {
			queryparam ="SELECT * FROM " + module + " WHERE email1='" + extractedemail + "';"; 
		}
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		switch(module) {
			case "Leads":
				MHM.getoperation(querystring,MHM.printoutputLeads,600);
				break;
			case "Vendors":
				MHM.getoperation(querystring,MHM.printoutputVendors,600);
				break;
			case "Users":
				MHM.getoperation(querystring,MHM.printoutputUsers,600);
				break;
			case "Accounts":
				MHM.getoperation(querystring,MHM.printoutputAccounts,600);
				break;
			default:
				MHM.getoperation(querystring,MHM.printoutput,600);
		}
		
	}
	
	MHM.getEventsFromContact = function(contactid, cpage) {
		MHM.cpEvent = cpage;
		
		// get current date
		var currentTime = new Date();
		currentTime.setTime(currentTime.getTime() - 1000*60*60*24);
		var month = currentTime.getMonth() + 1;
		var day = currentTime.getDate();
		var year = currentTime.getFullYear();
		var formatTime = year + "-" + month + "-" + day;
			
		queryparam ="SELECT * FROM events WHERE contact_id = " + contactid + " AND date_start > '" + formatTime + "'";
		if(MHM.cpEvent > 0) {
			queryparam += " LIMIT " + MHM.cpEvent*MHM.itemsperpage + "," + (MHM.cpEvent + 1)*MHM.itemsperpage;
		}
		queryparam += ";";
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.printoutputEvents,600);
	}
	
	MHM.getHelpDeskFromContact = function(contactid, cpage) {
		MHM.cpHelpDesk = cpage;		
		queryparam ="SELECT * FROM HelpDesk WHERE parent_id = " + contactid;
		if(MHM.cpHelpDesk > 0) {
			queryparam += " LIMIT " + MHM.cpHelpDesk*MHM.itemsperpage + "," + (MHM.cpHelpDesk + 1)*MHM.itemsperpage;
		}
		queryparam += ";";
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.printoutputHelpDesk,600);
	}

	MHM.getEmailFromContact = function(contactid, cpage) {
		MHM.cpEmail = cpage;		
		queryparam ="SELECT * FROM emails WHERE parent_id = "+ contactid+" ORDER BY createdtime desc";
		if(MHM.cpEmail > 0) {
			queryparam += " LIMIT " + MHM.cpEmail*MHM.itemsperpage + "," + (MHM.cpEmail + 1)*MHM.itemsperpage;
		}
		queryparam += ";";
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.printoutputEmails,600);
	}


	MHM.getFullEmailList = function(contactid) {
		queryparam ="SELECT * FROM emails WHERE parent_id = "+ contactid+" ORDER BY createdtime desc;";
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.AssignEmailList,600);
	}

	MHM.AssignEmailList = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Emails query failed");
		} else {
			if (response['result'][0] != null) {
				
				var size = response.result.length;			
				MHM.EmailList = new Array();

				for(i = 0;i < size;i++) {
					MHM.EmailList[response.result[i].id] = new Array(response.result[i].subject,response.result[i].date_start,response.result[i].type,response.result[i].assigned_user_id,response.result[i].description);
				}				
/*				
				for (var x in MHM.EmailList){
					for (j=0; j<5; j++){
						alert(MHM.EmailList[x][j]);
					}
				}
*/				
			}
		}
	}

	MHM.printoutput = function(obj) {
		var response = obj.data;
		if (typeof obj.data=='undefined' || response['success'] == false){
			MHM.displayerror(response, "Contact query failed");
			MHM.search(extractedText, 'Leads');
		} else {
			if (response['result'][0] != null) {
				recordid = response['result'][0]['id'];
				recordid = recordid.replace(/^[0-9]+x/,"");
				document.getElementById('name').innerHTML ="<a target='_blank' href=" + vtigerurl + "/index.php?action=DetailView&module=Contacts&parenttab=Marketing&record=" + recordid + ">" + response['result'][0]['firstname'] + " " + response['result'][0]['lastname'] + "</a>";	
				MHM.visible('nname');				
				document.getElementById('c_no').innerHTML = response['result'][0]['contact_no'];	
				MHM.visible('c_no');
				document.getElementById('ophone').innerHTML = response['result'][0]['phone'];	
				MHM.visible('ophone');
				document.getElementById('mphone').innerHTML = response['result'][0]['mobile'];	
				MHM.visible('mphone');
				document.getElementById('email').innerHTML = extractedText;
				MHM.visible('email');
				MHM.accountid = response['result'][0]['account_id'];
				MHM.matchid = response['result'][0]['id'];
				MHM.matchname = response['result'][0]['firstname'] + " " + response['result'][0]['lastname'];
				
				// get accounts
				if(MHM.accountid != '') {
					MHM.getaccount(MHM.accountid);
				}
				
				// get events
				MHM.getEventsFromContact(MHM.matchid, 0);
				
				// get trouber ticket (helpdesk)
				MHM.getHelpDeskFromContact(MHM.matchid, 0);
				
				// get email
				MHM.getFullEmailList(MHM.matchid);
				MHM.getEmailFromContact(MHM.matchid, 0);
				
				// switch to Match tab
				MHM.switchtab(0);
				
			} else {
				MHM.search(extractedText, 'Leads');
			}
		}
	}
	
	MHM.printoutputLeads = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Leads query failed");
			MHM.search(extractedText, 'Vendors');
		} else {
			if (response['result'][0] != null) {
				recordid = response['result'][0]['id'];
				recordid = recordid.replace(/^[0-9]+x/,"");				
				document.getElementById('match').innerHTML = "<div class='content'><dl><dt id='name_dt'>Name</dt><dd id='name'><a target='_blank' href=" + vtigerurl + "/index.php?action=DetailView&module=Leads&record=" + recordid + ">" + response['result'][0]['firstname'] + " " + response['result'][0]['lastname'] + "</a></dd><dt id='company_dt'>Company</dt><dd id='company'>" + response['result'][0]['company'] + "</dd><dt id='email_dt'>Email</dt><dd id='email'>" + extractedText + "</dd></dl></div><div class='content'><dl><dt id='c_no_dt'>Lead No</dt><dd id='c_no'>" + response['result'][0]['lead_no'] + "</dd><dt id='ophone_dt'>Office Phone</dt><dd id='ophone'>" + response['result'][0]['phone'] + "</dd><dt id='mphone_dt'>Mobile</dt><dd id='mphone'>" + response['result'][0]['mobile'] + "</dd></dl></div>";
				MHM.switchtab(0);
			} else {
				MHM.search(extractedText, 'Vendors');
			}
		}
	}
	
	MHM.printoutputVendors = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Vendor query failed");
			MHM.search(extractedText, 'Users');
		} else {
			if (response['result'][0] != null) {
				recordid = response['result'][0]['id'];
				recordid = recordid.replace(/^[0-9]+x/,"");				
				document.getElementById('match').innerHTML = "<div class='content'><dl><dt id='name_dt'>Vendor Name</dt><dd id='name'><a target='_blank' href=" + vtigerurl + "/index.php?action=DetailView&module=Vendors&record=" + recordid + ">" + response['result'][0]['vendorname'] + "</a></dd><dt id='company_dt'>GL Account</dt><dd id='company'>" + response['result'][0]['glacct'] + "</dd><dt id='email_dt'>Email</dt><dd id='email'>" + extractedText + "</dd></dl></div><div class='content'><dl><dt id='c_no_dt'>Vendor No</dt><dd id='c_no'>" + response['result'][0]['vendor_no'] + "</dd><dt id='ophone_dt'>Office Phone</dt><dd id='ophone'>" + response['result'][0]['phone'] + "</dd><dt id='mphone_dt'>Website</dt><dd id='mphone'>" + response['result'][0]['website'] + "</dd></dl></div>";
				MHM.switchtab(0);
			} else {
				MHM.search(extractedText, 'Users');
			}
		}
	}
	
	MHM.printoutputUsers = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "User query failed");
			MHM.search(extractedText, 'Accounts');
		} else {
			if (response['result'][0] != null) {
				recordid = response['result'][0]['id'];
				recordid = recordid.replace(/^[0-9]+x/,"");				
				document.getElementById('match').innerHTML = "<div class='content'><dl><dt id='name_dt'>Name</dt><dd id='name'><a target='_blank' href=" + vtigerurl + "/index.php?action=DetailView&module=Users&record=" + recordid + ">" + response['result'][0]['first_name'] + " " + response['result'][0]['last_name'] + "</a></dd><dt id='email_dt'>Email</dt><dd id='email'>" + extractedText + "</dd></dl></div><div class='content'><dl><dt id='c_no_dt'>User</dt><dd id='c_no'>" + response['result'][0]['user_name'] + "</dd><dt id='ophone_dt'>Office Phone</dt><dd id='ophone'>" + response['result'][0]['phone'] + "</dd><dt id='mphone_dt'>Mobile</dt><dd id='mphone'>" + response['result'][0]['mobile'] + "</dd></dl></div>";
				MHM.switchtab(0);
			} else {
				MHM.search(extractedText, 'Accounts');
			}
		}
	}
	
	MHM.printoutputAccounts = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Accounts query failed");
		} else {
			if (response['result'][0] != null) {
				recordid = response['result'][0]['id'];
				recordid = recordid.replace(/^[0-9]+x/,"");				
				document.getElementById('match').innerHTML = "<div class='content'><dl><dt id='name_dt'>Account Name</dt><dd id='name'><a target='_blank' href=" + vtigerurl + "/index.php?action=DetailView&module=Accounts&record=" + recordid + ">" + response['result'][0]['accountname'] + "</a></dd><dt id='email_dt'>Email</dt><dd id='email'>" + extractedText + "</dd><dt id='company_dt'>Website</dt><dd id='company'>" + response['result'][0]['website'] + "</dd></dl></div><div class='content'><dl><dt id='c_no_dt'>Account No</dt><dd id='c_no'>" + response['result'][0]['account_no'] + "</dd><dt id='ophone_dt'>Office Phone</dt><dd id='ophone'>" + response['result'][0]['phone'] + "</dd><dt id='mphone_dt'>Fax</dt><dd id='mphone'>" + response['result'][0]['fax'] + "</dd></dl></div>";
				MHM.switchtab(0);
			} else {
				var objEmail = document.getElementById('create_email')
				if(objEmail != null) {
					objEmail.value = extractedText;
				}
				MHM.switchtab(1);
			}
		}
	}
	
	MHM.printoutputEvents = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Events query failed");
		} else {
			if (response['result'][0] != null) {
				if(MHM.tpEvent == 0) {
					tabs.addTab("Calendar", {
						contentContainer: document.getElementById("calendar"),
						callback: MHM.callbackEvents
					});	
				}
				
				var size = response.result.length;			
				
				if(MHM.cpEvent == 0) {
					if(size % MHM.itemsperpage == 0) {
						MHM.tpEvent = size / MHM.itemsperpage;
					} else {
						MHM.tpEvent = (size - size % MHM.itemsperpage) / MHM.itemsperpage + 1;
					}
				}
				
				if(size > MHM.itemsperpage) {
					size = MHM.itemsperpage;
				}
				
				var content = '<table width="100%" cellpadding="3" cellspacing="0" border="1"><tr><td colspan="5" align="right">';
				if(MHM.cpEvent == 0) {
					content += '&laquo;&nbsp;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getEventsFromContact(\'' + response.result[0].contact_id + '\',' + (MHM.cpEvent - 1) + ')">&laquo;</a>&nbsp;';
				}				
				if(MHM.cpEvent == MHM.tpEvent - 1) {
					content += '&raquo;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getEventsFromContact(\'' + response.result[0].contact_id + '\',' + (MHM.cpEvent + 1) + ')">&raquo;</a>';
				}
				content += '</td></tr><tr><td class="email_header">Date</td><td class="email_header">Time</td><td class="email_header">Type</td><td class="email_header">Name</td><td class="email_header">Assigned To</td></tr>';
				for(i = 0;i < size;i++) {
					recordid = response.result[i].id;
					recordid = recordid.replace(/^[0-9]+x/,"");	
					content += '<tr><td class="email_content">' + response.result[i].date_start + '</td><td class="email_content">' + response.result[i].time_start + '</td><td class="email_content">Call</td><td class="email_content"><a target="_blank" href="' + vtigerurl + '/index.php?action=DetailView&module=Calendar&record=' + recordid + '&activity_mode=Events&viewtype=calendar">' + response.result[i].subject + '</a></td><td class="email_content">' + MHM.listUsers[response.result[i].assigned_user_id] + '</td></tr>';					
				}
				content += '</table>';
				document.getElementById('calendar').innerHTML = content;
			}
		}
	}	
	
	MHM.callbackEvents = function() {
		gadgets.window.adjustHeight();
	}
	
	MHM.printoutputHelpDesk = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "HelpDesk query failed");
		} else {
			if (response['result'][0] != null) {
				if(MHM.tpHelpDesk == 0) {
					tabs.addTab("HelpDesk", {
						contentContainer: document.getElementById("helpdesk"),
						callback: MHM.callbackHelpDesk
					});	
				}
				
				var size = response.result.length;			
				
				if(MHM.cpHelpDesk == 0) {
					if(size % MHM.itemsperpage == 0) {
						MHM.tpHelpDesk = size / MHM.itemsperpage;
					} else {
						MHM.tpHelpDesk = (size - size % MHM.itemsperpage) / MHM.itemsperpage + 1;
					}
				}
				
				if(size > MHM.itemsperpage) {
					size = MHM.itemsperpage;
				}
				
				var content = '<table width="100%" cellpadding="3" cellspacing="0" border="1"><tr><td colspan="8" align="right">';
				if(MHM.cpHelpDesk == 0) {
					content += '&laquo;&nbsp;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getHelpDeskFromContact(\'' + response.result[0].parent_id + '\',' + (MHM.cpHelpDesk - 1) + ')">&laquo;</a>&nbsp;';
				}				
				if(MHM.cpHelpDesk == MHM.tpHelpDesk - 1) {
					content += '&raquo;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getHelpDeskFromContact(\'' + response.result[0].parent_id + '\',' + (MHM.cpHelpDesk + 1) + ')">&raquo;</a>';
				}
				content += '</td></tr><tr><td class="email_header">Ticket No</td><td class="email_header">Title</td><td class="email_header">Status</td><td class="email_header">Priority</td><td class="email_header">Severity</td><td class="email_header">Days</td><td class="email_header">Hours</td><td class="email_header">Assigned To</td></tr>';				
				for(i = 0;i < size;i++) {
					content += '<tr><td class="email_content">' + response.result[i].ticket_no + '</td><td class="email_content"><a href="#" onclick="MHM.detailviewHelpDesk(\'' + response.result[i].id + '\',\'view\');">' + response.result[i].ticket_title + '</a></td><td class="email_content">' + response.result[i].ticketstatus + '</td><td class="email_content">' + response.result[i].ticketpriorities + '</td><td class="email_content">' + response.result[i].ticketseverities + '</td><td class="email_content">' + response.result[i].days + '</td><td class="email_content">' + response.result[i].hours + '</td><td class="email_content">' + MHM.listUsers[response.result[i].assigned_user_id] + '</td></tr>';
				}
				content += '</table>';
				document.getElementById('helpdesk').innerHTML = content;
				gadgets.window.adjustHeight();
			}
		}
	}	

	MHM.callbackHelpDesk = function() {
		gadgets.window.adjustHeight();
	}
	
	MHM.detailviewHelpDesk = function(hdId, mode) {
		getstring = "operation=retrieve&sessionName=" + MHM.sessionname + "&id=" + hdId;
		if(mode == 'view') {
			MHM.getoperation(getstring,MHM.printDVHelpDesk,600);
		} else {
			MHM.getoperation(getstring,MHM.printEditHelpDesk,600);
		}
	}
	
	MHM.printDVHelpDesk = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Retrieve failed");
			}
		else {
			var description = (response.result.description == '') ? 'No Description' : response.result.description;
			var solution = (response.result.description == '') ? 'No Solution' : response.result.solution;
			var content = '<table width="100%" cellpadding="3" cellspacing="0" border="1"><tr><td class="email_header">Ticket No</td><td class="email_header">Title</td><td class="email_header">Status</td><td class="email_header">Priority</td><td class="email_header">Severity</td><td class="email_header">Days</td><td class="email_header">Hours</td><td class="email_header">Assigned To</td></tr><tr><td class="email_content">' + response.result.ticket_no + '</td><td class="email_content">' + response.result.ticket_title + '</td><td class="email_content">' + response.result.ticketstatus + '</td><td class="email_content">' + response.result.ticketpriorities + '</td><td class="email_content">' + response.result.ticketseverities + '</td><td class="email_content">' + response.result.days + '</td><td class="email_content">' + response.result.hours + '</td><td class="email_content">' + MHM.listUsers[response.result.assigned_user_id] + '</td></tr><tr><td colspan="8">' + description + '</td></tr><tr><td colspan="7">' + solution + '</td><td><input id="button" onclick="MHM.detailviewHelpDesk(\'' + response.result.id + '\',\'edit\');" type=button value="Edit"><br><input id="button" onclick="MHM.getHelpDeskFromContact(\'' + MHM.matchid + '\', 0);" type=button value="Return"></td></tr></table>';
			document.getElementById('helpdesk').innerHTML = content;
			gadgets.window.adjustHeight();
		}
	}
	
	MHM.printEditHelpDesk = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Retrieve failed");
			}
		else {
			var description = (response.result.description == '') ? 'No Description' : response.result.description;
			var solution = (response.result.description == '') ? 'No Solution' : response.result.solution;
			var content = '<div id="status_message_hd" style="color: #FF0000"></div><table width="100%" cellpadding="3" cellspacing="0" border="1"><tr><td class="email_header">Ticket No</td><td class="email_header">Title</td><td class="email_header">Status</td><td class="email_header">Priority</td><td class="email_header">Severity</td><td class="email_header">Days</td><td class="email_header">Hours</td><td class="email_header">Assigned To</td></tr><tr><td class="email_content"><input id="ticket_no" type="text" value="' + response.result.ticket_no + '"></td><td class="email_content"><input id="title" type="text" value="' + response.result.ticket_title + '" size="60" style="width:100%"></td><td class="email_content"><select id="status"><option value="Minor">Open</option><option value="Major">In Progress</option><option value="Feature">Wait For Response</option><option value="Critical">Closed</option></select></td><td class="email_content"><select id="priority"><option value="Low">Low</option><option value="Normal">Normal</option><option value="High">High</option><option value="Urgent">Urgent</option></select></td><td class="email_content"><select id="serverity"><option value="Minor">Minor</option><option value="Major">Major</option><option value="Feature">Feature</option><option value="Critical">Critical</option></select></td><td class="email_content"><input id="days" type="text" value="' + response.result.days + '"></td><td class="email_content"><input id="hours" type="text" value="' + response.result.hours + '"></td><td class="email_content"><select id="assigned_to">';
			
			for (var x in MHM.listUsers){
					content += "<option value='"+x+"'>"+MHM.listUsers[x]+"</option>";
				}
				
			content +='</select><input type="hidden" name="parent_id" id="parent_id" value="' + response.result.parent_id + '"></td></tr><tr><td colspan="8"><textarea id="description" rows="3" style="width:100%">' + description + '</textarea></td></tr><tr><td colspan="7"><textarea id="solution" rows="3" style="width:100%">' + solution + '</textarea></td><td><input id="button" onclick="MHM.updatehelpdesk(\''+response.result.id+'\');" type=button value="Save"><br><input id="button" onclick="MHM.getHelpDeskFromContact(\'' + MHM.matchid + '\', 0);" type=button value="Return"></td></tr></table>';
			document.getElementById('helpdesk').innerHTML = content;
			gadgets.window.adjustHeight();
		}
	}

	
	MHM.printoutputEmails = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Email query failed");
		} else {
			if (response['result'][0] != null) {
				if(MHM.tpEmail == 0) {
					tabs.addTab("Emails", {
						contentContainer: document.getElementById("emailtab"),
						callback: MHM.callbackEmail
					});	
				}
				
				var size = response.result.length;			

				if(MHM.cpEmail == 0) {
					if(size % MHM.itemsperpage == 0) {
						MHM.tpEmail = size / MHM.itemsperpage;
					} else {
						MHM.tpEmail = (size - size % MHM.itemsperpage) / MHM.itemsperpage + 1;
					}
				}
				
				if(size > MHM.itemsperpage) {
					size = MHM.itemsperpage;
				}
				
				var content = '<table width="100%" cellpadding="1" cellspacing="2"><tr><td><input id="email_search" type="text" style="width:100%" /></td><td style="width:50px;"><input id="button" onclick="MHM.emailsearch(\'' + response.result[0].parent_id + '\',0)" type=button value="Go"></td><td style="width:10px"><input id="email_checkbox" type="checkbox" style = "margin-left: 0px; margin-right: 0px;"/></td><td class="email_content">Subject only</td><td align="right"></td>';
				if(MHM.cpEmail == 0) {
					content += '&laquo;&nbsp;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getEmailFromContact(\'' + response.result[0].parent_id + '\',' + (MHM.cpEmail - 1) + ')">&laquo;</a>&nbsp;';
				}				
				if(MHM.cpEmail == MHM.tpEmail - 1) {
					content += '&raquo;';
				} else {
					content += '<a href="javascript:void(0);" onclick="MHM.getEmailFromContact(\'' + response.result[0].parent_id + '\',' + (MHM.cpEmail + 1) + ')">&raquo;</a>';
				}
				content += '</tr></table><table width="100%" cellpadding="3" cellspacing="0" border="1">';
				content += '<tr><td class="email_header">Subject</td><td style="width:60px" class="email_header">Date Sent</td><td class="email_header">Assigned To</td></tr>';				
				for(i = 0;i < size;i++) {
					recordid = response.result[i].id;
					recordid = recordid.replace(/^[0-9]+x/,"");	
					content += '<tr><td class="email_content"><a target="_blank" href="' + vtigerurl + '/index.php?action=DetailView&module=Emails&record=' + recordid + '">' + response.result[i].subject + '</a></td><td class="email_content">' + response.result[i].date_start + '</td><td class="email_content">' + MHM.listUsers[response.result[i].assigned_user_id] + '</td></tr>';
				}
				content += '</table>';
				document.getElementById('emailtab').innerHTML = content;
			}
		}
	}	

	MHM.callbackEmail = function() {
		gadgets.window.adjustHeight();
	}

	MHM.printSearchEmailValue = function(contactid,cpage){
		MHM.cpEmail = cpage;
		MHM.tpEmail = MHM.totalrecord / MHM.itemsperpage;		
		var start = MHM.cpEmail*MHM.itemsperpage;
		if (MHM.cpEmail >= MHM.tpEmail - 1){
			var end = MHM.totalrecord;
		}else{
			var end = start + MHM.itemsperpage;
		}
//		alert("cp ="+MHM.cpEmail+" TP = "+MHM.tpEmail+"start = "+start+" end = "+end+" totalrecord = " + MHM.totalrecord);
		var content = '<table width="100%" cellpadding="1" cellspacing="2"><tr><td><input id="email_search" type="text" style="width:100%" /></td><td style="width:50px;"><input id="button" onclick="MHM.emailsearch(\'' + contactid + '\',0)" type=button value="Go"></td><td style="width:10px"><input id="email_checkbox" type="checkbox" style = "margin-left: 0px; margin-right: 0px;"/></td><td class="email_content">Subject only</td><td align="right"></td>';
		if(MHM.cpEmail == 0) {
			content += '&laquo;&nbsp;';
		} else {
			content += '<a href="javascript:void(0);" onclick="MHM.printSearchEmailValue(\''+contactid+'\',' + (MHM.cpEmail - 1) + ')">&laquo;</a>&nbsp;';
		}				
		if(MHM.cpEmail >= MHM.tpEmail - 1) {
			content += '&raquo;';
		} else {
			content += '<a href="javascript:void(0);" onclick="MHM.printSearchEmailValue(\''+contactid+'\',' + (MHM.cpEmail + 1) + ')">&raquo;</a>';
		}
		content += '</tr></table><table width="100%" cellpadding="3" cellspacing="0" border="1">';
		content += '<tr><td class="email_header">Subject</td><td class="email_header">Date Sent</td><td class="email_header">Assigned To</td></tr>';				
		for(i = start;i < end;i++) {
			content += '<tr><td class="email_content"><a target="_blank" href="' + vtigerurl + '/index.php?action=DetailView&module=Emails&record=' + recordid + '">' + MHM.SearchValue[i][0] + '</a></td><td class="email_content">' + MHM.SearchValue[i][1] + '</td><td class="email_content">' + MHM.listUsers[MHM.SearchValue[i][3]] + '</td></tr>';
		}
		content += '</table>';
		document.getElementById('emailtab').innerHTML = content;
		
	}
	
	MHM.emailsearch = function(contactid, cpage){
		var value = document.getElementById('email_search').value;
		var check = document.getElementById('email_checkbox').checked;
		value = value.toUpperCase();
		MHM.cpEmail = cpage;		
		if (check == false) {
//			queryparam += " AND (subject LIKE '%" + value +"%' OR description LIKE '%"+value+"%')";
			MHM.SearchValue = new Array();
			MHM.totalrecord = 0;
			for (var x in MHM.EmailList){
//				alert(MHM.EmailList[x][4]);
				var tempsub = MHM.EmailList[x][0].toUpperCase();
				var tempdes = MHM.EmailList[x][4].toUpperCase();
				if ( tempsub.indexOf(value) >0 || tempdes.indexOf(value) >0){					
					MHM.SearchValue[MHM.totalrecord] = new Array(MHM.EmailList[x][0],MHM.EmailList[x][1],MHM.EmailList[x][2],MHM.EmailList[x][3],MHM.EmailList[x][4]);
					MHM.totalrecord++;
				}
			}
			MHM.cpEmail = 0;
			MHM.tpEmail = 0;
			MHM.printSearchEmailValue(contactid,0);
/*			
			alert(MHM.totalrecord);
			for (var y=0; y<MHM.totalrecord; y++){
				for (var k=0; k<5; k++){
					alert(MHM.SearchValue[y][k]);
				}
				
			}
*/			
/*			
			for (var y in MHM.SearchValue){
				for (var k=0; k<5; k++){
					alert(MHM.SearchValue[y][k]);
				}
			}
*/			
		}else{
			MHM.SearchValue = new Array();
			MHM.totalrecord = 0;
			for (var x in MHM.EmailList){
//				alert(MHM.EmailList[x][4]);
				var tempsub = MHM.EmailList[x][0].toUpperCase();
				var tempdes = MHM.EmailList[x][4].toUpperCase();
				if ( tempsub.indexOf(value) >0){					
					MHM.SearchValue[MHM.totalrecord] = new Array(MHM.EmailList[x][0],MHM.EmailList[x][1],MHM.EmailList[x][2],MHM.EmailList[x][3],MHM.EmailList[x][4]);
					MHM.totalrecord++;
				}
			}
			MHM.cpEmail = 0;
			MHM.tpEmail = 0;
			MHM.printSearchEmailValue(contactid,0);
		}
		
	}
	
	MHM.switchtab = function(n) {
		tabs.setSelectedTab(n);
		if (n==1) {
			gadgets.window.adjustHeight(140);
		} else {
			gadgets.window.adjustHeight();
		}

	}
		
	MHM.getaccount = function(accountid) {
		getstring = "operation=retrieve&sessionName=" + MHM.sessionname + "&id=" + MHM.accountid;
		MHM.getoperation(getstring,MHM.printaccount,600);
	}
	
	MHM.printaccount = function(obj) {
		var response = obj.data;
		if (response['success'] == false){
			MHM.displayerror(response, "Retrieve failed");
			}
		else {
			recordid = response['result']['id'];
			recordid = recordid.replace(/^[0-9]+x/,"");
			document.getElementById('account').innerHTML = "<a href=" + vtigerurl + "/index.php?module=Accounts&action=DetailView&record=" + recordid + ">" + response['result']['accountname'] + "</a>";
			MHM.visible('account');
		}
	}

	// Step2: 
	MHM.challenge = function() {
		MHM.getchallenge = "operation=getchallenge&username=" + userName;
		MHM.getoperation(MHM.getchallenge,MHM.challengeresponse,0);
	}
	
	MHM.changeModule = function() {
		var createModule = document.getElementById('create_module');
		var selectedModule = createModule.options[createModule.selectedIndex].value;
		var createContent = document.getElementById('create');
		
		var eventCreation = "";
		if(MHM.matchid != '') {
			eventCreation = "<option value='Event'>Event</option>";
		}
		
		switch (selectedModule) {
			case "Accounts":
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>Account Name</dt><dd><input id='account_name' type='text'></dd><dt>Account No</dt><dd><input id='accountno' type='text'></dd><dt>Phone</dt><dd><input id='account_phone' type='text' value='" + extractedPhone + "'></dd></dl></div><div class='content'><dl><dt>Email</dt><dd><input id='create_email' type='text' value='" + extractedText + "'></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts' selected='selected'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createaccount()' type=button value='Add'></div></form>";
				break;
			case "Leads":
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>First Name</dt><dd><input id='lead_firstname' type='text' value='" + firstname + "'></dd><dt>Last Name</dt><dd><input id='lead_lastname' type='text' value='" + lastname + "'></dd><dt>Email</dt><dd><input id='create_email' type='text' value='" + extractedText + "'></dd></dl></div><div class='content'><dl><dt>Phone</dt><dd><input id='lead_phone' type='text' value='" + extractedPhone + "'></dd><dt>Company</dt><dd><input id='lead_company' type='text'></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads' selected='selected'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createlead()' type=button value='Add'></div></form>";
				break;
			case "Potentials":
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>Potential Name</dt><dd><input id='potential_name' type='text'></dd><dt>Expected Close Date</dt><dd><input id='expected_close_date' type='text'></dd><dt>Account Name</dt><dd><div id='search_account'><input id='create_account_name' type='text' onkeyup='MHM.searchaccount()'><input id='create_account_id' type='hidden'><div id='search_account_result'><ul id='acc_list'></ul></div></div></dd></dl></div><div class='content'><dl><dt>Amount</dt><dd><input id='potential_amount' type='text'></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials' selected='selected'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createpotential()' type=button value='Add'></div></form>";
				break;
			case "Vendors":
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>Vendor Name</dt><dd><input id='vendor_name' type='text'></dd><dt>Email</dt><dd><input id='vendor_email' type='text' value='" + extractedText + "'></dd><dt>Phone</dt><dd><input id='vendor_phone' type='text' value='" + extractedPhone + "'></dd></dl></div><div class='content'><dl><dt>Category</dt><dd><input id='vendor_category' type='text'></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors' selected='selected'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createvendor()' type=button value='Add'></div></form>";
				break;
			case "FAQ":
				createContent.innerHTML = '<div id="createfaq" onclick="MHM.hideSearchResult()"><div id="status_message"></div><form id="create_form" name="create_form"><div class="content"><textarea style="width:98%" rows="3" id="faq_question">Question:</textarea><dl><dt>Status<font color="red">*</font></dt><dd><select id="faq_status"><option value="Draft">Draft</option></select></dd><dt>Category</dt><dd><select id="faq_category"><option value="General">General</option></select></dd><dt>Product</dt><dd><div id="search_product"><input id="create_product_name" type="text" onkeyup="MHM.searchproduct()"><div id="search_product_result"><ul id="product_list"></ul></div><input id="create_product_id" type="hidden"></div></dd></dl></div><div class="content"><textarea style="width:98%" rows="3" id="faq_answer">Answer:</textarea></dd><dl><dt>Module</dt><dd><select id="create_module" onchange="MHM.changeModule()"><option value="Contacts">Contacts</option><option value="Accounts">Accounts</option><option value="Leads">Leads</option><option value="Potentials">Potentials</option><option value="Vendors">Vendors</option><option value="FAQ" selected="selected">FAQ</option><option value="HelpDesk">Help Desk</option>' + eventCreation + '</select></dd></dl></div><div id="new"><input id="button" onclick="MHM.createfaq()" type=button value="Add"></div></form></div>';
				break;
			case "HelpDesk":
			
				var content = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>Title</dt><dd><input id='title' type='text'></dd><dt>Assigned To</dt><dd><select id='assigned_to'>";
				
				for (var x in MHM.listUsers){
					content += "<option value='"+x+"'>"+MHM.listUsers[x]+"</option>";
				}
				
				content += "</select></dd><dt>Priority</dt><dd><select id='priority'>";


				for (var i=0; i<MHM.totalticketpriorities; i++){
					content += "<option value= '"+MHM.ticketpriorities[i].value+"'>"+MHM.ticketpriorities[i].label+"</option>";
	//				alert("label = "+MHM.ticketpriorities[i].label+" value = "+MHM.ticketpriorities[i].value);
				}
				
				content += "</select></dd><dt>Serverity</dt><dd><select id='serverity'>";
				
				for (var i=0; i<MHM.totalticketseverities; i++){
					content += "<option value= '"+MHM.ticketseverities[i].value+"'>"+MHM.ticketseverities[i].label+"</option>";
				}
				
				content += "</select></dd><dt>Status</dt><dd><select id='status'>";
				
				for (var i=0; i<MHM.totalticketstatus; i++){
					content += "<option value= '"+MHM.ticketstatus[i].value+"'>"+MHM.ticketstatus[i].label+"</option>";
				}
				
				content +="</select></dd><dt>Product</dt><dd><div id='search_product'><input id='create_product_name' type='text' onkeyup='MHM.searchproduct()'><div id='search_product_result'><ul id='product_list'></ul></div><input id='create_product_id' type='hidden'></div></dd></dl></div><div class='content'><dl><dt>Days</dt><dd><input id='days' type='text'></dd><dt>Hours</dt><dd><input id='hours' type='text'></dd><dd style='padding:0px;margin:0px;'><textarea id='description' rows='3' style='width:100%;'></textarea></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk' selected='selected'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createhelpdesk()' type=button value='Add'></div></form>";
				
				createContent.innerHTML = content;
				break;
			case "Event":
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>Event Name</dt><dd><input id='event_name' type='text'></dd><dt>Event Type</dt><dd><select id='event_type'><option value='Call'>Call</option><option value='Meeting'>Meeting</option></select></dd><dt>Event starts at</dt><dd><select onchange='changeTime();' id='starthr' style='width:auto;'><option value='12'>12</option><option value='01'>01</option><option value='02'>02</option><option value='03'>03</option><option value='04'>04</option><option value='05'>05</option><option value='06'>06</option><option value='07'>07</option><option value='08'>08</option><option value='09'>09</option><option value='10'>10</option><option value='11'>11</option></select><select onchange='changeTime();' id='startmin' name='startmin' style='width:auto;'><option value='00'>00</option><option value='05'>05</option><option value='10'>10</option><option value='15'>15</option><option value='20'>20</option><option value='25'>25</option><option value='30'>30</option><option value='35'>35</option><option value='40'>40</option><option value='45'>45</option><option value='50'>50</option><option value='55'>55</option></select><select onchange='changeTime();' id='startfmt' name='startfmt' style='width:auto;'><option value='am'>AM</option><option value='pm'>PM</option></select><input id='date_start' style='width:36.3%;'><img border='0' id='jscal_trigger_date_start' title='Set Date' alt='Set Date' src='http://tiger04.borugroup.com/vtiger510_gai/jscalendar/img.gif'></dd><dt>Event ends at</dt><dd><select id='endhr' style='width:auto;'><option value='12'>12</option><option value='01'>01</option><option value='02'>02</option><option value='03'>03</option><option value='04'>04</option><option value='05'>05</option><option value='06'>06</option><option value='07'>07</option><option value='08'>08</option><option value='09'>09</option><option value='10'>10</option><option value='11'>11</option></select><select id='endmin' name='startmin' style='width:auto;'><option value='00'>00</option><option value='05'>05</option><option value='10'>10</option><option value='15'>15</option><option value='20'>20</option><option value='25'>25</option><option value='30'>30</option><option value='35'>35</option><option value='40'>40</option><option value='45'>45</option><option value='50'>50</option><option value='55'>55</option></select><select id='endfmt' name='startfmt' style='width:auto;'><option value='am'>AM</option><option value='pm'>PM</option></select><input id='date_end' style='width:36.3%;'><img border='0' id='jscal_trigger_date_end' title='Set Date' alt='Set Date' src='http://tiger04.borugroup.com/vtiger510_gai/jscalendar/img.gif'></dd><dt>Location</dt><dd><input id='location' type='text'></dd></dl></div><div class='content'><dl><dt>Status</dt><dd><select id='status'><option value='Planned'>Planned</option><option value='Held'>Held</option><option value='Not Held'>Not Held</option></select></dd><dt>Priority</dt><dd><select id='priority'><option value='High'>High</option><option value='Medium'>Medium</option><option value='Low'>Low</option></select></dd><dd style='padding:0px;margin:0px;'><textarea id='description' rows='3' style='width:100%;'>Description</textarea></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='FAQ'>Help Desk</option><option value='Event' selected='selected'>Event</option></select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createevent()' type=button value='Add'></div></form>";
				
				Calendar.setup({
					inputField : "date_start", 
					ifFormat : "%Y-%m-%d", 
					showsTime : false, 
					button : "jscal_trigger_date_start", 
					singleClick : true, 
					align: "cR",
					step : 1
				});
				
				Calendar.setup({
					inputField : "date_end", 
					ifFormat : "%Y-%m-%d", 
					showsTime : false, 
					button : "jscal_trigger_date_end", 
					singleClick : true, 
					align: "cR",
					step : 1
				});
				
				break;
			default:
				createContent.innerHTML = "<div id='status_message'></div><form id='create_form' name='create_form'><div class='content'><dl><dt>First Name</dt><dd><input id='create_firstname' type='text' value='" + firstname + "'></dd><dt>Last Name</dt><dd><input id='create_lastname' type='text' value='" + lastname + "'></dd><dt>Email</dt><dd><input id='create_email' type='text' value='" + extractedText + "'></dd><dt>Account Name</dt><dd><div id='search_account'><input id='create_account_name' type='text' onkeyup='MHM.searchaccount()'><input id='create_account_id' type='hidden'><div id='search_account_result'><ul id='acc_list'></ul></div></div></dd></dl></div><div class='content'><dl><dt>Office Phone</dt><dd><input id='create_phone' type='text' value='" + extractedPhone + "'></dd><dt>Mobile</dt><dd><input id='create_mobile' type='text'></dd><dt>Module</dt><dd><select id='create_module' onchange='MHM.changeModule()'><option value='Contacts'>Contacts</option><option value='Accounts'>Accounts</option><option value='Leads'>Leads</option><option value='Potentials'>Potentials</option><option value='Vendors'>Vendors</option><option value='FAQ'>FAQ</option><option value='HelpDesk'>Help Desk</option>" + eventCreation + "</select></dd></dl></div><div id='new'><input id='button' onclick='MHM.createcontact()' type=button value='Add'></div></form>";
		}
		if (selectedModule == 'FAQ') {
			gadgets.window.adjustHeight(200);
		} else if (selectedModule == 'HelpDesk') {
			gadgets.window.adjustHeight(200);
		} else if (selectedModule == 'Event') {
			gadgets.window.adjustHeight(210);
		} else {
			gadgets.window.adjustHeight(140);
		}		
	}	
	
	MHM.searchaccount = function() {
		var accountValue = document.getElementById('create_account_name').value;
		queryparam ="SELECT * FROM Accounts WHERE accountname LIKE '%" + accountValue + "%' LIMIT 5;"; 
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.fillaccount,360);
	}
	
	MHM.fillaccount = function(obj) {
		var result = obj.data.result;
		var searchAccountResult = document.getElementById('search_account_result');	
		var content = document.getElementById('acc_list');	
		content.innerHTML = "";
		for(i = 0;i < result.length;i++) {			
			content.innerHTML += "<li><a href='#' onclick=\"MHM.setAccountName('" + result[i].id + "','" + result[i].accountname + "')\">" + result[i].accountname + "</a></li>";
		}		
		searchAccountResult.style.display = "block";
	}
	
	MHM.hideSearchResult = function() {
		var searchAccountResult = document.getElementById('search_account_result');	
		if(searchAccountResult != null) {
			searchAccountResult.style.display = "none";
		}
	}

	MHM.setAccountName = function(accountId, accountName) {
		document.getElementById('create_account_id').value = accountId;
		document.getElementById('create_account_name').value = accountName;
		MHM.hideSearchResult();
	}

	MHM.searchproduct = function() {
		var productValue = document.getElementById('create_product_name').value;
		queryparam ="SELECT * FROM Products WHERE productname LIKE '%" + productValue + "%' LIMIT 5;"; 
		queryparam = encodeURI(queryparam);
		querystring = "operation=query&sessionName=" + MHM.sessionname + "&query=" + queryparam;
		MHM.getoperation(querystring,MHM.fillproduct,360);
	}
	
	MHM.fillproduct = function(obj) {
		var result = obj.data.result;
		var searchProductResult = document.getElementById('search_product_result');	
		var content = document.getElementById('product_list');	
		content.innerHTML = "";
		for(i = 0;i < result.length;i++) {			
			content.innerHTML += "<li><a href='#' onclick=\"MHM.setProductName('" + result[i].id + "','" + result[i].productname + "')\">" + result[i].productname + "</a></li>";
		}		
		searchProductResult.style.display = "block";
	}
	
	MHM.hideSearchProductResult = function() {
		var searchProductResult = document.getElementById('search_product_result');	
		if(searchProductResult != null) {
			searchProductResult.style.display = "none";
		}
	}

	MHM.setProductName = function(productId, productName) {
		document.getElementById('create_product_id').value = productId;
		document.getElementById('create_product_name').value = productName;
		MHM.hideSearchProductResult();
	}

	MHM.createcontact = function() {
		var contactData = {};
			contactData.firstname = document.getElementById('create_firstname').value;
			contactData.lastname = document.getElementById('create_lastname').value;
			contactData.email = document.getElementById('create_email').value;
			contactData.phone = document.getElementById('create_phone').value;
			contactData.mobile = document.getElementById('create_mobile').value;
			contactData.account_id = document.getElementById('create_account_id').value;
			contactData.assigned_user_id = MHM.userId;
			
		jsonObject = gadgets.json.stringify(contactData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Contacts";
		MHM.postoperation(postdata,MHM.createresponse,0);
	}

	MHM.createaccount = function(){
		var accountData = {};
		accountData.accountname = document.getElementById('account_name').value;
		accountData.accountno = document.getElementById('accountno').value;
		accountData.phone = document.getElementById('account_phone').value;
		accountData.email1 = document.getElementById('create_email').value;
		accountData.assigned_user_id = MHM.userId;
		jsonObject = gadgets.json.stringify(accountData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Accounts";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}	

	MHM.createproduct = function(){
		var productData = {};
		productData.productname = document.getElementById('productname').value;
		productData.taxpercentage = document.getElementById('product_taxpercentage').value;
		productData.unit_price = document.getElementById('product_unit_price').value;
		productData.qtyinstock = document.getElementById('product_qtyinstock').value;
		jsonObject = gadgets.json.stringify(productData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Products";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}	

	MHM.createservice = function(){
		var serviceData = {};
		serviceData.productname	= document.getElementById('servicename').value;
		serviceData.taxpercentage = document.getElementById('service_taxpercentage').value;
		serviceData.unit_price = document.getElementById('service_unit_price').value;
		serviceData.qtyinstock = document.getElementById('service_qtyinstock').value;
		jsonObject = gadgets.json.stringify(serviceData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Services";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}	

	MHM.createlead = function(){
		var leadData = {};
		leadData.firstname = document.getElementById('lead_firstname').value;
		leadData.lastname = document.getElementById('lead_lastname').value;
		leadData.company = document.getElementById('lead_company').value;
		leadData.email = document.getElementById('create_email').value;
		leadData.phone = document.getElementById('lead_phone').value;
		leadData.assigned_user_id = MHM.userId;
		jsonObject = gadgets.json.stringify(leadData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Leads";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}	
	
	MHM.createpotential = function(){
		var potentialData = {};
			potentialData.potentialname = document.getElementById('potential_name').value;		
			potentialData.amount = document.getElementById('potential_amount').value;	
			potentialData.sales_stage = "Prospecting";
			potentialData.closingdate = document.getElementById('expected_close_date').value;	
			potentialData.related_to = document.getElementById('create_account_id').value;
			potentialData.assigned_user_id = MHM.userId;			
		
		jsonObject = gadgets.json.stringify(potentialData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Potentials";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}

	MHM.createvendor = function(){
		var vendorData = {};
		vendorData.vendorname = document.getElementById('vendor_name').value;
		vendorData.category = document.getElementById('vendor_category').value;
		vendorData.phone = document.getElementById('vendor_phone').value;
		vendorData.email = document.getElementById('vendor_email').value;
		jsonObject = gadgets.json.stringify(vendorData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Vendors";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}	
	
	MHM.createfaq = function(){
		var question = document.getElementById('faq_question').value;
		var answer = document.getElementById('faq_answer').value;
		var status = document.getElementById('faq_status').value;
		
		if (question == ''){
			alert('You have to type your question');
		}else if(answer == '') {
			 alert('You have to type your answer');
		}else if (status == ''){
			alert('You have to choose the status');
		}
		
	}
	
	MHM.createhelpdesk = function(){
		var helpdeskData = {};
		helpdeskData.ticket_title = document.getElementById('title').value;
		var obj = document.getElementById('assigned_to');
		helpdeskData.assigned_user_id = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('priority');
		helpdeskData.priority = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('serverity');
		helpdeskData.serverity = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('status');
		helpdeskData.ticketstatus = obj.options[obj.selectedIndex].value;
		helpdeskData.hours = document.getElementById('hours').value;
		helpdeskData.days = document.getElementById('days').value;
		helpdeskData.description = document.getElementById('description').value;
		helpdeskData.product_id = document.getElementById('create_product_id').value;
//		for (var x in helpdeskData)
//			alert(x+" "+ helpdeskData[x]);
		jsonObject = gadgets.json.stringify(helpdeskData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "HelpDesk";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}
	
	MHM.updatehelpdesk = function(hd_id){
		var helpdeskData = {};
		helpdeskData.id = hd_id;
		helpdeskData.ticket_title = document.getElementById('title').value;
		var obj = document.getElementById('assigned_to');
		helpdeskData.assigned_user_id = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('priority');
		helpdeskData.priority = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('serverity');
		helpdeskData.serverity = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('status');
		helpdeskData.ticketstatus = obj.options[obj.selectedIndex].value;
		helpdeskData.hours = document.getElementById('hours').value;
		helpdeskData.days = document.getElementById('days').value;
		helpdeskData.description = document.getElementById('description').value;
		helpdeskData.parent_id = MHM.matchid;
//		helpdeskData.product_id = document.getElementById('create_product_id').value;
//		for (var x in helpdeskData)
//			alert(x+" "+ helpdeskData[x]);
		jsonObject = gadgets.json.stringify(helpdeskData);
		var postdata = {};
			postdata.operation = "update";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "HelpDesk";
		MHM.postoperation(postdata,MHM.updatehelpdesk_response,0);
			
	}
	
	
	MHM.updatehelpdesk_response = function(obj) {
		var response = obj.data;
		
		var statusMessage = document.getElementById('status_message_hd');
		statusMessage.style.display = "block";					
		
		if (response['success'] == false){
			MHM.displayerror(response, "Update HelpDesk failed");
		} else {
			statusMessage.innerHTML = "Update HelpDesk successfull";			
		}
	}

	MHM.createevent = function(){
		var eventData = {};
		eventData.subject = document.getElementById('event_name').value;		
		var obj = document.getElementById('event_type');
		eventData.activitytype = obj.options[obj.selectedIndex].value;		
		eventData.description = document.getElementById('description').value;		
		eventData.location = document.getElementById('location').value;
		var obj = document.getElementById('status');
		eventData.eventstatus = obj.options[obj.selectedIndex].value;		
		var obj = document.getElementById('priority');
		eventData.taskpriority = obj.options[obj.selectedIndex].value;
		eventData.taskstatus = 'Not Started';
		// start
		var obj = document.getElementById('starthr');
		var hr = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('startmin');
		var min = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('startfmt');
		var fmt = obj.options[obj.selectedIndex].value;
		eventData.time_start = hr + ":" + min;
		eventData.date_start = document.getElementById('date_start').value;
		// end
		var obj = document.getElementById('endhr');
		var hr = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('endmin');
		var min = obj.options[obj.selectedIndex].value;
		var obj = document.getElementById('endfmt');
		var fmt = obj.options[obj.selectedIndex].value;
		eventData.time_end = hr + ":" + min;
		eventData.due_date = document.getElementById('date_end').value;
		eventData.duration_hours = 1;
		eventData.duration_minutes = 0;
		eventData.visibility = 'Public';
		eventData.contact_id = MHM.matchid;		
		eventData.assigned_user_id = MHM.userId;		
		
		jsonObject = gadgets.json.stringify(eventData);
		var postdata = {};
			postdata.operation = "create";
			postdata.sessionName = MHM.sessionname;
			postdata.element= jsonObject;
			postdata.elementType = "Events";
		MHM.postoperation(postdata,MHM.createresponse,0);		
	}
	
	MHM.createresponse = function(obj) {
		var response = obj.data;
		var statusMessage = document.getElementById('status_message');
		statusMessage.style.display = "block";
		if (response['success'] == false){
			MHM.displayerror(response, "Add failed");
		} else {
			statusMessage.innerHTML = "Add Successful";
			document.create_form.reset();			
		}
		setTimeout("MHM.hideStatusMessage()", 5000);
	}

	MHM.hideStatusMessage = function() {
		var statusMessage = document.getElementById('status_message');
		statusMessage.style.display = "none";
		statusMessage.innerHTML = "";
	}

	GetTabContent = function(ModuleName) {
		querystring = "operation=describe&sessionName=" + MHM.sessionname+"&elementType="+ModuleName;
		MHM.getoperation(querystring,MHM.createresponse,360);
	}
	
	MHM.displayerror = function(response, string) {
		//msg.createDismissibleMessage(string + ": " + response['error']['message']);
	}

	_2digit = function(no) {
		if(no < 10) return "0" + no;
		else return "" + no;
	}
	
	splitDateVal = function(dateval) {
		var userDateFormat = "yyyy-mm-dd";
		var datesep;
		var dateelements = new Array(3);
		if (dateval.indexOf("-")>=0) datesep="-"
		else if (dateval.indexOf(".")>=0) datesep="."
		else if (dateval.indexOf("/")>=0) datesep="/"
		
		switch (userDateFormat) {
			case "yyyy-mm-dd" : 
								dateelements[0]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length) //dd
								dateelements[1]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep)) //mm
								dateelements[2]=dateval.substring(0,dateval.indexOf(datesep)) //yyyyy
								break;
			case "mm-dd-yyyy" : 
								dateelements[0]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep))
								dateelements[1]=dateval.substring(0,dateval.indexOf(datesep))
								dateelements[2]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length)
								break;
			case "dd-mm-yyyy" : 
								dateelements[0]=dateval.substring(0,dateval.indexOf(datesep))
								dateelements[1]=dateval.substring(dateval.indexOf(datesep)+1,dateval.lastIndexOf(datesep))
								dateelements[2]=dateval.substr(dateval.lastIndexOf(datesep)+1,dateval.length)
		}
		
		return dateelements;
	}
	
	getdispDate = function(tempDate) {
		var datefmt = "";
		var dd = _2digit(parseInt(tempDate.getDate(),10));
		var mm = _2digit(parseInt(tempDate.getMonth(),10)+1);
		var yy = tempDate.getFullYear();
		if(datefmt == '%d-%m-%Y') return dd+'-'+mm+'-'+yy;
		else if(datefmt == '%m-%d-%Y') return mm+'-'+dd+'-'+yy;
		else return yy+'-'+mm+'-'+dd;
	}
	
	changeTime = function() {
		// get params
		var fmt = document.getElementById('startfmt').value;
		var hour = parseInt(document.getElementById('starthr').value,10);
		var min = parseInt(document.getElementById('startmin').value,10);
		var date = document.getElementById('date_start').value;
		
		// next date
		var dateval1 = date.replace(/^\s+/g, '').replace(/\s+$/g, '');
		var dateelements1=splitDateVal(dateval1);
		dd1=parseInt(dateelements1[0],10);
		mm1=dateelements1[1];
		yyyy1=dateelements1[2];
		var date1 = new Date();	
		date1.setYear(yyyy1);
		date1.setMonth(mm1-1,dd1+1);
		var tempdate = getdispDate(date1);
		
		if(fmt == 'pm') {
			if(hour == 11) {
				date = tempdate;
				hour = 12;fmt = 'am';
			} else if(hour == 12) {
				hour = 1;fmt = 'pm';
			} else {
				hour = hour + 1;
			}
		} else if(fmt == 'am') {
			if(hour == 11) {
				hour = 12;fmt = 'pm';
			} else if(hour == 12) {
				hour = 1;fmt = 'am';
			} else {
				hour = hour + 1;
			}		
		} else {
			hour = hour + 1;
			if(hour == 24) {
				hour = 0;
				date =  tempdate;
			}
		}
		
		hour = _2digit(hour);
		min = _2digit(min);
		document.getElementById('endfmt').value = fmt;
		document.getElementById('endhr').value = hour;
		document.getElementById('endmin').value = min;
		document.getElementById('date_end').value = date;
	}


